package com.cswnode.Service.impl;

import com.cswnode.Dao.CommentMapper;
import com.cswnode.Entity.Comment;
import com.cswnode.Service.CommentService;
import com.cswnode.Service.DiscussPostService;
import com.cswnode.Util.Constant;
import com.cswnode.Util.SensitiveUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;
import org.unbescape.html.HtmlEscape;

import java.beans.Transient;
import java.util.List;

/**
 * @author csw
 * @create 2020/9/23 14:43
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private SensitiveUtil sensitiveUtil;

    @Override
    public List<Comment> findCommentByLimit(Integer entityId, Integer entityType, int offset, int limit) {
        return commentMapper.findCommentByLimit(entityId,entityType,offset,limit);
    }

    @Override
    public int findNumByEntity(Integer entityId, Integer entityType) {
        return commentMapper.findNumByEntity(entityId,entityType);
    }
    //声明事务
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    @Override
    public int insertComment(Comment comment) {
        if (comment == null){
            throw new IllegalArgumentException("参数不能为空");
        }
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveUtil.filter(comment.getContent()));
        int rows = commentMapper.insertComment(comment);
        if (rows == 0){
            throw new IllegalArgumentException("评论失败！");
        }
        if (comment.getEntityType() == Constant.ENTITY_TYPE_POST){
            int commenCount = commentMapper.findNumByEntity(comment.getEntityId(),comment.getEntityType());
            discussPostService.updateCommentCount(comment.getEntityId(),commenCount);
        }
        return 0;
    }

    @Override
    public Comment findCommentById(int id) {
        Comment comment = commentMapper.findCommentById(id);
        if (comment == null){
            throw new IllegalArgumentException("查询不到该评论");
        }
        return comment;
    }


}
